// pages/message/index.js
// import GtPush from '../../libs/gtpush-min'
// import {
//   bindCid
// } from '../../api/login'
import {
  getMsgUserList,
  removeMsgUser
} from '../../api/ChatMsgController.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 'message',
    top: 0,
    msgUserList: [], //聊天用户记录
    params: {
      pageNum: 1,
      pageSize: 20
    },
    notifyData: {},
    notifyFlag: {},
    triggered: false //是否下拉加载
  },
  //获取聊天列表
  async getMsgUList() {
    if (!wx.getStorageSync('userId')) {
      return this.setData({
        msgUserList: []
      })
    }
    this.setData({
      'params.userId': wx.getStorageSync('userId')
    })
    const res = await getMsgUserList(this.data.params)
    res.list.forEach(ele => ele.createTime = wx.utils.formatMsgTime(ele.createTime))
    this.setData({
      msgUserList: res.list
    })
  },
  //获取通知列表
  getNotifyData() {
    if (!wx.getStorageSync('notifyData')) return this.setData({
      notifyData: {},
      notifyFlag: {},
      allFlag: false
    })
    const notifyData = wx.getStorageSync('notifyData')
    const notifyFlag = wx.getStorageSync('notifyFlag')
    for (let key in notifyData) {
      if (notifyData[key][0]) notifyData[key][0].createTime = wx.utils.formatMsgTime(notifyData[key][0].createTime)
    }
    this.setData({
      notifyData,
      notifyFlag
    })
  },
  //删除聊天用户
  async delMessage(e) {
    const msgUserId = e.mark.msgUserId
    await removeMsgUser({
      msgUserId,
      userId: wx.getStorageSync('userId')
    })
    const newList = this.data.msgUserList.filter(ele => ele.userId !== msgUserId)
    this.setData({
      msgUserList: newList
    })
    //接收消息角标
    this.getTabBar().setData({
      count: app.count - e.mark.count
    })
    app.count = app.count - e.mark.count
  },
  //去私聊页面
  toChat(ev) {
    wx.navigateTo({
      url: `/pkgMessage/pages/chat/index?userId=${ev.mark.userInfo.userId}&nickName=${ev.mark.userInfo.nickName}&count=${ev.mark.unreadCount}`,
    })
  },
  //去系统消息页面
  toSystemMessage(ev) {
    wx.navigateTo({
      url: `/pkgMessage/pages/systemMessage/index?title=${ev.mark.title}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //动态获取右上角胶囊按钮距离顶部位置
    const menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      top: menu.top - 5
    })
    wx.onSocketMessage(({
      data
    }) => {
      const msg = JSON.parse(data)
      const index = this.data.msgUserList.findIndex(ele => msg.fromId === ele.userId)
      if (index !== -1) {
        this.setData({
          ['msgUserList[' + index + '].unreadCount']: +this.data.msgUserList[index].unreadCount + 1,
          ['msgUserList[' + index + '].content']: msg.content,
          ['msgUserList[' + index + '].createTime']: '刚刚'
        })
      } else {
        msg.createTime = '刚刚'
        msg.unreadCount = 1
        msg.userId = msg.fromId
        this.setData({
          msgUserList: [msg, ...this.data.msgUserList]
        })
      }
    })
    // GtPush.setDebugMode(true)
    // GtPush.init({
    //   appid: 'FyRFIRkddTAAIm2nhssbyA',
    //   onClientId: (res) => {
    //     //个推ClientId回调，拿到cid后将其上报到服务端
    //     console.info(`onClientId: ${res.cid}`)
    //     bindCid(res.cid).then((res) => {
    //     })
    //   },

    //   onlineState: (data) => {
    //     //个推ClientId在线状态回调
    //     console.info(`onlineState: ${data.online}`)
    //   },

    //   onPushMsg: (res) => {
    //     //推送消息回调
    //     console.info(`onPushMsg`, res.message)
    //   },

    //   onError: (res) => {
    //     //错误回调
    //     console.info(`onError`, res.error)
    //   }
    // })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3,
        count: app.count
      })
    }
    wx.onSocketMessage(({
      data
    }) => {
      if (data === 'ok') return
      //接收消息角标
      this.getTabBar().setData({
        count: app.count + 1
      })
      app.count = app.count + 1
      const msg = JSON.parse(data)
      if (!msg.fromId) return
      const index = this.data.msgUserList.findIndex(ele => msg.fromId === ele.userId)
      if (index !== -1) {
        this.setData({
          ['msgUserList[' + index + '].unreadCount']: +this.data.msgUserList[index].unreadCount + 1,
          ['msgUserList[' + index + '].content']: msg.content,
          ['msgUserList[' + index + '].createTime']: '刚刚'
        })
      } else {
        msg.createTime = '刚刚'
        msg.unreadCount = 1
        msg.userId = msg.fromId
        this.setData({
          msgUserList: [msg, ...this.data.msgUserList]
        })
      }
    })
    this.getMsgUList()
    this.getNotifyData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  /**
   * 页面下拉刷新
   */
  onScrollRefresh() {
    this.getNotifyData()
    this.setData({
      triggered: false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})